<?php
namespace App\Goods\Services;

use App\ApiBaseController;
use App\Exceptions\GoodsException;
use App\Goods\Models\CommonName;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Overtrue\Pinyin\Pinyin;
use Exception;
use App\Goods\Handles\GoodsHandle;
use Psr\SimpleCache\InvalidArgumentException;

class CommonNameService extends ApiBaseController
{
    use GoodsHandle;

    /**
     * 生成spu
     * @param $data
     * @return string
     */
    public function setSpu($data)
    {
        $spu_sn = $this->setSpuHandle($data['name']);
        // 闪存spu和通用名名称用于验证, 闪存存在一天时间
        Cache::put('spu_'.$spu_sn, $data['name'], 84600);
        return $spu_sn;
    }


    /**
     * 添加通用名
     * @param $data
     * @return bool
     * @throws GoodsException
     */
    public function saveCommonName($data)
    {
        // 验证spu有效性
        $cache_name = Cache::get('spu_'.$data['spu']); // 后续改成pull
        if($data['name'] != $cache_name){
            throw new GoodsException('验证SPU错误，SPU已失效或者不存在！');
        }
        // 验证spu格式是否正确
        if(!$this->checkSpuHandle($data['spu'], $data['name'])){
            throw new GoodsException('验证SPU错误，SPU格式不正确！');
        }
        if(CommonName::where('spu_sn', $data['spu'])->count()){
            throw new GoodsException('SPU已存在，不能重复添加！');
        }
        // 添加数据
        $create_data = [
            'name' => $data['name'],
            'spu_sn'=> $data['spu']
        ];
        DB::beginTransaction();
        try {
            if(!$common_name = CommonName::create($create_data)){
                throw new GoodsException('添加失败！');
            }
            // 添加通用名关联属性
            $attr = json_decode($data['attr']);
            $attr_arr = [];

            foreach($attr as $v){
                if(is_array($v->value)){
                    $v->value = json_encode($v->value);
                }
                $attr_arr[$v->id] = [
                    'value' => $v->value
                ];

            }
            $res = $common_name->hasAttr()->sync($attr_arr);
            if(!$res){
                throw new GoodsException('添加失败！');
            }
            DB::commit();
            return $common_name;
        }catch (Exception $exception){
            DB::rollBack();
            throw new GoodsException('添加失败！');
        }
    }

    /**
     * 查询通用名详情
     * @param $id
     * @return CommonName object
     * @throws GoodsException
     */
    public function getInfo($id)
    {
        $common_name = CommonName::select(['id', 'spu_sn', 'name', 'created_at'])->with(['hasAttr' => function ($table){
             $table->select(['name', 'value', 'default', 'type']);
        }])->find($id);
        if(!$common_name){
            throw new GoodsException('商品通用名不存在！');
        }
        return $common_name;
    }




}
